<?php
require_once "weixin/jssdk.php";
class WeixinJs {
    private $jssdk;

    public function __construct($appId, $appSecret) {
        $this->jssdk = new JSSDK(WX_AppID, WX_AppSecret);
    }

    public function getSignPackage() {
        return $this->jssdk->getSignPackage();
    }
    
    
    public function getClientSignPackage($clienturl) {
        return $this->jssdk->getClientSignPackage($clienturl);
    }
    
    public function getAccessToken()
    {
        return $this->jssdk->getAccessToken();
    }
    
    public function downloadToUpyun($media_id)
    {
        $access_token = $this->getAccessToken();
        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$access_token.'&media_id='.$media_id;
        
        function http_get_data($url) {
        
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
            curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt ( $ch, CURLOPT_URL, $url );
            ob_start ();
            curl_exec ( $ch );
            $return_content = ob_get_contents ();
            ob_end_clean ();
        
            $return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
        
            curl_close($ch);
        
            return $return_content;
        }
        
        $return_content = http_get_data($url);
        
        $name = md5(uniqid(mt_rand(), true)) . '.jpg';
        $local_path = 'product/' .date("Y-m-d",time()) ;
        
        $filename = $local_path.'/'. $name;
        
        if(!is_dir(DIR_IMAGE . $local_path))
        {
            mkdir(DIR_IMAGE . $local_path);
        }
        
        $fp= @fopen(DIR_IMAGE . $filename,"a"); //将文件绑定到流 
        fwrite($fp,$return_content); //写入文件
        fclose($fp);

        $save_filename = '/' . date("Y/m/d",time()) . '/'  . $name;

        $upyun = new UpyunHelper("fourboy", "admin", "fourboy123");

        return $upyun->uploadWithPath($filename, $save_filename);
    }
}